<?php
declare (strict_types = 1);

namespace app\model\mysql;

use think\Model;

class ProductSpecValue extends Model {

    protected $hidden = ["is_delete"];

    protected $name = "product_spec_value";

    protected $createTime = "created_time";

    protected $updateTime = "updated_time";

    protected $autoWriteTimestamp = true;

    public function spec() {
        return $this->hasOne(ProductSpec::class, "id", "spec_id");
    }


    public function getList(int $specId = 0, string $field = "id, spec_id, name") : array {

        $model = $this;
        $model = $model->where("is_delete", "<>", 1);
        if ($specId > 0) {
            $model = $model->where("spec_id", $specId);
        }
        $result = $model->field($field)->select();

        return $result ? $result->toArray() : [];
    }

    public function isExistSpecValue(int $specId = 0, string $name = "", $isIncludeDelete =false) : bool {
        if ($specId <=0 || empty($name)) {
            return false;
        }

        $where = [
            ["spec_id", "=", $specId],
            ["name", "=", $name],
        ];

        if (!$isIncludeDelete) {
            $where[] = ["is_delete", "<>", 1];
        }

        $result = $this->where($where)->find();

        return $result && $result->id > 0 ? true : false;
    }

    public function saveData(array $data = []) : bool {
        if (empty($data["spec_id"]) || empty($data["name"])) {
            return false;
        }
        $isExist = $this->isExistSpecValue($data["spec_id"], $data["name"], true);
        if ($isExist) {
            $where = [
                ["spec_id", "=", $data["spec_id"]],
                ["name", "=", $data["name"]],
            ];
            return $this->where($where)->save([
                "is_delete" => 0
            ]);
        }

        return $this->save($data);
    }

    public function getListByIds($ids = []) : array {

        $result = $this->withJoin(["spec" => ["name"]], "LEFT")
            ->whereFieldRaw("product_spec_value.is_delete", 0)
            ->whereIn("product_spec_value.id", $ids)->select();

        return $result->toArray();
    }
}